package com.hsmpay.mobile.action.account.qian48;

import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.OrderTypeUtil;
import com.hsmpay.common.util.URLDecoderTools;
import com.hsmpay.common.util.bank.BankCardTypeUtil;
import com.hsmpay.mobile.action.account.fc.PurchaseBaseAction;
import com.hsmpay.mobile.dao.trans.TransOrderDao;
import com.hsmpay.mobile.pojo.bank.BankCode;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.terminal.TerminalPrivileges;
import com.hsmpay.mobile.service.bank.BankCodeService;
import com.hsmpay.mobile.service.user.UserTransLimitService;
import com.hsmpay.mobile.service.zytl.ZYTLParamService;
import com.hsmpay.mobile.util.icc.ME30DataDecode;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.service.ds.impl.ZYTLPayServiceImpl;
import com.hsmpay.utils.TimeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 千48余额查询 action
 *
 * @author 颜铃璋
 * @date 2013-8-27
 */
@Controller("q4BalanceEnquiryAction")
@Scope("prototype")
public class Q4BalanceEnquiryAction extends Q4BaseAction {
    private static final long serialVersionUID = 1L;
    private static Logger log = Logger.getLogger(Q4BalanceEnquiryAction.class);
    public static final String BALANCEINQUIRY_FUNCKEY = "BALANCEINQUIRY";
    @Resource(name = "bankCodeService")
    public BankCodeService<BankCode, Long> bankCodeService;
    @Resource(name = "transOrderDao")
    public TransOrderDao transOrderDao;
    @Resource(name = "userTransLimitService")
    private UserTransLimitService<BasePojo, Long> userTransLimitService;
    /**
     * 余额查询
     *
     * @return
     * @throws Exception
     */
    public String balanceEnquiry() throws Exception {
        log.debug("--- BalanceEnquiry() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));
        userId = Long.parseLong(getJsonString("userId"));
        functionKey = getJsonString("functionKey");
        merchantOrderId = getJsonString("merchantOrderId");
        merchantOrderTime = getJsonString("merchantOrderTime");
        terminalId = getJsonString("terminalId");
        accountNumber = getJsonString("accountNumber");
        pin = getJsonString("pin");
        track2Data = getJsonString("track2Data");
        track3Data = getJsonString("track3Data");
        dynamicKeyData = getJsonString("dynamicKeyData");
        senderSign = getJsonString("senderSign");
        serviceInfo = getJsonString("serviceInfo");
        terminalInfo = getJsonString("terminalInfo");
        mac = getJsonString("mac");
        icCardYu = getJsonString("icCardYu");//IC卡 域
        encryType = getJsonString("encryType");//IC卡 加密类型

        transType = "100002";
        application = "BalanceEnquiry.Req";
        log.debug("userId = " + userId);//用户ID
        log.debug("functionKey = " + functionKey);//用户ID
        log.debug("clientType = " + clientType);//
        log.debug("terminalTypeId = " + terminalTypeId);//

        log.debug("merchantOrderId = " + merchantOrderId);//商户订单
        log.debug("merchantOrderTime = " + merchantOrderTime);//商户订单时间
        log.debug("terminalId = " + terminalId);//终端代码
        log.debug("accountNumber = " + accountNumber);//主账户
        log.debug("pin = " + pin);//个人身份标识码
        log.debug("track2Data = " + track2Data);//磁道2数据
        log.debug("track3Data = " + track3Data);//磁道2数据

        log.debug("dynamicKeyData = " + dynamicKeyData);// 动态密钥数据

        log.debug("senderSign = " + senderSign);//发送方数字签名
        log.debug("serviceInfo = " + serviceInfo);//服务信息
        log.debug("terminalInfo = " + terminalInfo);//终端信息 手机串号、号码、os、序列号等
        log.debug("mac = " + mac);
        log.debug("icCardYu = " + icCardYu);
        log.debug("encryType = " + encryType);

        if (null == userId) {
            log.warn("余额查询时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.warn("余额查询时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }
        if (StringUtils.isBlank(merchantOrderId)) {
            log.warn("余额查询时, 传入参数merchantOrderId为空");
            sendAppErrorMsg("6001", "merchantOrderId");
            return null;
        }
        if (StringUtils.isBlank(merchantOrderTime)) {
            log.warn("余额查询时, 传入参数merchantOrderTime为空");
            sendAppErrorMsg("6001", "merchantOrderTime");
            return null;
        }
        if (StringUtils.isBlank(accountNumber)) {
            log.warn("余额查询时, 传入参数accountNumber为空");
            sendAppErrorMsg("6001", "accountNumber");
            return null;
        }
        if (StringUtils.isBlank(pin)) {
            log.warn("余额查询时, 传入参数pin为空");
            sendAppErrorMsg("6001", "pin");
            return null;
        }
        if (StringUtils.isBlank(track2Data)) {
            log.warn("余额查询时, 传入参数track2Data为空");
            sendAppErrorMsg("6001", "track2Data");
            return null;
        }

        track3Data = "";
        User user = null;
        Qian4SendLog send = null;
        Map<String, Object> result = null;
        try {
            functionKey = "BALANCEINQUIRY";
            if (!checkPIV(functionKey)) {
                log.warn("余额查询时, 银行接口暂停使用！");
                return null;
            }

            user = userService.getUserById(userId);
            //判断用户的查询余额次数是否超限
            Map<String, Object> map=userTransLimitService.userBalanceEnquiryLimit(userId, -3L, accountNumber);
            if (map != null) {
                sendAppErrorMsg(map.get("code").toString(), map.get("value").toString());
                return null;
            }
            if (null != user) {
                User user1=new User();
                user1.setId(userId);
                user1.setDeleted(0);
                user= userService.searchEntity(user1);
                if(user==null){
                    Map<String, Object> resMap = new HashMap<String, Object>();
                    log.warn("余额查询时, 用户Id=" + userId + " 对应的用户不存在!");
                    resMap.put("reqCode", "6004");
                    resMap.put("reqMsg", "用户："+userId+ " 该用户被销户或暂停使用！");
                    resMap.put("channelId", "");
                    sendAppMsg(resMap);
                    return null;
                }
                //判断日期是否是今天
                Date date = new Date();
                String today = DateConvertUtil.dateString(date, "yyyyMMdd");//
                if (!merchantOrderTime.startsWith(today)) {
                    merchantOrderId = getMerchantOrderId(date, user.getLoginName());
                    merchantOrderTime = DateConvertUtil.dateString(date, "yyyyMMddHHmmss");
                }

                //屏蔽伪卡
                if (transRefuseCardService.isRefuseCard(accountNumber)) {
                    sendAppErrorMsg("6073", accountNumber);
                    return null;
                }

                if ("1".equals(encryType)) {
                    track2Data = ME30DataDecode.decryptTrace2(track2Data);
                    //icCardYu.replace(oldChar, newChar)
                } else if ("2".equals(encryType)) {
                    String trackOData = getJsonString("trackOData");
                    String[] trackA = ME30DataDecode.decryptTrace2_aic(trackOData, track2Data);
                    track2Data = trackA[0];
                    track3Data = trackA[1];
                }
                track2Data = track2Data.replaceAll("F", "");//屏蔽二磁道有F的情况


                send = new Qian4SendLog();
                send.setCallType(0);
                send.setRoleId(roleId);
                send.setUserId(userId);
                send.setApplication("BalanceEnquiry.Req");
                send.setOrderTypeId(OrderTypeUtil.BALANCE_ENQUIRY);
                send.setSendTime(date);
                send.setSendSeqId(TimeUtils.getTimeToString());
                send.setTransType("100001");
                //send.setMerchantId(merchantId);//商户代码#
                //send.setTerminalId(terminalId);//终端代码
                send.setPlatformId(platformId);//平台号#
                send.setMerchantOrderId(merchantOrderId);//商户ID#
                send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));
                send.setAccountNumber(accountNumber);
                //交易流水号
                //send.setBankOrderNum("100040");
                send.setCurrency("156");
                send.setPin(pin);
                send.setTrack2Data(track2Data);
                send.setTrack3Data(track3Data);
                send.setDynamicKeyData(dynamicKeyData);
                send.setSenderSign(senderSign);
                send.setServiceInfo(serviceInfo);
                send.setTerminalInfo(terminalInfo);
                send.setMac(mac);
                send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP
                //send.setMsgExt(msgExt);
                //send.setMisc(misc);
                send.setIcCardYu(icCardYu);
                send.setCardTypeN(StringUtils.isEmpty(icCardYu) ? 1 : 2);//1 磁条卡 2 IC卡
                //查询数据库中通道信息的方法
                TerminalPrivileges tp = terminalPrivilegesService.searchPrivilegesByFunctionKey(BALANCEINQUIRY_FUNCKEY);
                Integer channelCode = tp.getTchannel().intValue();

                Tchannel tc = null;
                switch (channelCode) {
                    case PurchaseBaseAction.TC_ECB:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_ECB);
                        send = ds_ECBService.initSend(send,tc);
                        break;
                    case PurchaseBaseAction.TC_RuiSheng:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_RuiSheng);
                        send = ds_RuiShengService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_RuiSheng_GT:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_RuiSheng_GT);
                        send = ds_RuiShengGTService.initSend(send,tc);
                        break;
                    case PurchaseBaseAction.TC_ZHONGYI:
                        break;
                    case PurchaseBaseAction.TC_POSP:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_POSP);
                        send = ds_pospService.initSend(send,tc,user.getId());
                        break;
                    case PurchaseBaseAction.TC_EPOINT:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_EPOINT);
                        send = ds_ideaioeService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_Uinpay:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_Uinpay);
                        send = ds_uinpayPayService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_YinShengBao:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_YinShengBao);
                        send = ds_yinShengBaoService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_POS:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_POS);
                        send = ds_posService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_ZHIFUTONG:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_ZHIFUTONG);
                        send = ds_zhifutongService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_HANXIN:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_HANXIN);
                        send = ds_HanXinService.initSend(send, tc);
                        break;
                    case PurchaseBaseAction.TC_ZHONGLAN:
                        tc = tchannelService.searchMobileTchannelByCode(PurchaseBaseAction.TC_ZHONGLAN);
                        send = ds_zhongLanService.initSend(send, tc);
                        break;
                }

                //添加 日志
                long sendId = qian4SendLogService.insertEntity(send);
                send.setId(sendId);

                BalanceResult br = null;
                switch (channelCode) {
                    case PurchaseBaseAction.TC_ECB:
                        br = ds_ECBService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_RuiSheng:
                        br = ds_RuiShengService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_RuiSheng_GT:
                        br = ds_RuiShengGTService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_ZHONGYI:
                        br = ds_zytlPayService.balance(send);
                        break;
                    case PurchaseBaseAction.TC_POSP:
                        br = ds_pospService.balanceEnquiry(send);
                        break;
                    default:
                        ZYTLPayServiceImpl zytlPayService1 = new ZYTLPayServiceImpl();
                        br = zytlPayService1.balance(send);
                        break;
                    case PurchaseBaseAction.TC_EPOINT://EPoint通道值40
                        br = ds_ideaioeService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_YinShengBao:
                        br = ds_yinShengBaoService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_Uinpay:
                        br = ds_uinpayPayService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_POS:
                        br = ds_posService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_ZHIFUTONG:
                        br = ds_zhifutongService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_HANXIN:
                        br = ds_HanXinService.balanceEnquiry(send);
                        break;
                    case PurchaseBaseAction.TC_ZHONGLAN:
                        br = ds_zhongLanService.balanceEnquiry(send);
                        break;
                }

                result = new HashMap<String, Object>();
                if (!"0000".equals(br.getReqCode())) {
                    log.debug("余额查询失败");
                    result.put("bankResp", "0");
                    result.put("reqCode", br.getReqCode());
                    result.put("reqMsg", br.getReqMsg());
                    qian4SendLogService.updateResCodeMassage(send.getId(), br.getReqCode(), br.getReqMsg());
                } else {
                    if (StringUtils.isEmpty(br.getBankName())) {//查询开户行
                        br.setBankName(bankCodeService.searchBankNameByCard(br.getAccountNumber()));
                    }
                    if (StringUtils.isEmpty(br.getCardType())) {//查询信用卡
                        br.setCardType("借记卡");
                        if (BankCardTypeUtil.isCreditCard(br.getAccountNumber())) {
                            br.setCardType("信用卡");
                        }
                    }

                    result.put("bankResp", "1");
                    result.put("accountNumber", br.getAccountNumber());
                    result.put("bankName", StringUtils.isEmpty(br.getBankName()) ? "" : br.getBankName());
                    result.put("cardType", StringUtils.isEmpty(br.getCardType()) ? "" : br.getCardType());
                    result.put("accountBalance", br.getBalance());
                    result.put("balanceCurrency", StringUtils.isEmpty(br.getBalanceCurrency()) ? "RMB" : br.getBalanceCurrency());
                    result.put("reqCode", br.getReqCode());
                    result.put("reqMsg", br.getReqMsg());
                    log.debug("余额查询时, 收款成功！");
                    qian4SendLogService.updateResCodeMassage(send.getId(), br.getReqCode(), br.getReqMsg());
                }

                //检测 银联返回结果 如果是有违法嫌疑的  那么将暂停该笔结算
                transRefuseCardService.checkRefuseClear(user.getId(), br.getReqMsg(), merchantOrderId, send.getOrderTypeId());
                sendAppMsg(result);
            } else {
                log.warn("查询余额是, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            user = null;
            send = null;
            result = null;
        }
        return null;
    }
    /**
     * 获取交易流水号
     * @return
     */
    public Integer getBankOrderNum() throws SQLException {
        return transOrderDao.searchPospTransId();
    }
}
